package com.fellansoft.moviescollection.business;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import com.fellansoft.moviescollection.gui.ViewConstants;
import com.fellansoft.moviescollection.data.CoverFlowElement;
import com.fellansoft.moviescollection.data.Movie;
import com.fellansoft.moviescollection.persistence.DatabaseHelper;
import com.fellansoft.moviescollection.persistence.PersistenceConstants;
import com.fellansoft.moviescollection.utils.ApplicationVariables;

import java.util.Date;
import java.util.List;

/**
* Created by IntelliJ IDEA.
* User: Codrin      ->naty
* Date: 5/15/12
* Time: 12:11 AM
* To change this template use File | Settings | File Templates.
*/

public class DataManager {
   /**
     * Single instance for this manager
     */
    private static DataManager instance;
    private static Movie movie;
    /**
     * Intent filter for the intents sent when the movie was saved successfully
     */
    private static IntentFilter saveMovieSuccessIntentFilter;

    /**
     * Intent filter for the intents sent when the movie was not saved successfully
     */
    private static IntentFilter saveMovieErrorIntentFilter;

    /**
     * Receiver for the intents sent when the movie was saved successfully to database
     */
    private static BroadcastReceiver saveMovieSuccessReceiver;

    /**
     * Receiver for the intents sent when there was a problem saving the new movie to database
     */
    private static BroadcastReceiver saveMovieErrorReceiver;

    /**
     * Intent filter for the intents sent when the folders were received from database
     */
    private static IntentFilter receiveFoldersSuccessIntentFilter;

    /**
     * Intent filter for the intents sent when the folders were not received from database
     */
    private static IntentFilter receiveFoldersErrorIntentFilter;

    /**
     * Receiver for the intents sent when the folders were received from database
     */
    private static BroadcastReceiver receiveFoldersSuccessReceiver;

    /**
     * Receiver for the intents sent when the folders were not received from database
     */
    private static BroadcastReceiver receiveFoldersErrorReceiver;

        /**
     * Intent filter for the intents sent when the movies were received from database
     */
    private static IntentFilter receiveMoviesSuccessIntentFilter;

    /**
     * Intent filter for the intents sent when the movies were not received from database
     */
    private static IntentFilter receiveMoviesErrorIntentFilter;

    /**
     * Receiver for the intents sent when the movies were received from database
     */
    private static BroadcastReceiver receiveMoviesSuccessReceiver;

    /**
     * Receiver for the intents sent when the movies were not received from database
     */
    private static BroadcastReceiver receiveMoviesErrorReceiver;

    /**
     * ArrayList for movies from database
     */
    // private static ArrayList<Movie> moviesArrayList;

    /**
     * List for movies in CoverFlowElement format from database
     */
    private static List<CoverFlowElement> moviesList;

    /**
     * The application context used to register receivers
     */
    private Context context;

    private IntentFilter deleteMovieSuccessIntentFilter;
    private BroadcastReceiver deleteMovieSuccessReceiver;
    private IntentFilter deleteMovieErrorIntentFilter;
    private BroadcastReceiver deleteMovieErrorReceiver;
    private IntentFilter updateMovieSuccessIntentFilter;
    private BroadcastReceiver updateMovieSuccessReceiver;
    private IntentFilter updateMovieErrorIntentFilter;
    private BroadcastReceiver updateMovieErrorReceiver;
    private IntentFilter getMovieByIdSuccessIntentFilter;
    private BroadcastReceiver getMovieByIdSuccessReceiver;
    private IntentFilter getMovieByIdErrorIntentFilter;
    private BroadcastReceiver getMovieByIdErrorReceiver;
    private IntentFilter getMoviesFromSearchSuccessIntentFilter;
    private BroadcastReceiver getMoviesFromSearchSuccessReceiver;
    private IntentFilter getMoviesFromSearchErrorIntentFilter;
    private BroadcastReceiver getMoviesFromSearchErrorReceiver;

    /**
     * Method used to return the single instance of this manager
     *
     * @return Instance of this manager
     */
    public static DataManager getInstance() {
        if (instance == null)
            instance = new DataManager();
        return instance;
    }

    /**
     * Private constructor
     */
    private DataManager() {
        //Get the context
        context = ApplicationVariables.getApplicationContext();
    }


    public void requestSaveMovie(String title, Date releaseDate, String description, String director, boolean[] categories, Boolean watchList, Boolean favorite, Float ownRating, Uri coverPhoto, List<Uri> photos) {

        //Register the receivers
        if (saveMovieSuccessIntentFilter == null)
            saveMovieSuccessIntentFilter = new IntentFilter(PersistenceConstants.PC_MOVIE_SAVED_SUCCESSFULLY);
        if (saveMovieSuccessReceiver == null)
            saveMovieSuccessReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context localContext, Intent intent) {
                    context.unregisterReceiver(saveMovieSuccessReceiver);

                    //Notify the success to Activity
                    context.sendBroadcast(new Intent(BusinessConstants.BC_MOVIE_SAVED_SUCCESSFULLY));
                }
            };
        context.registerReceiver(saveMovieSuccessReceiver, saveMovieSuccessIntentFilter);

        if (saveMovieErrorIntentFilter == null)
            saveMovieErrorIntentFilter = new IntentFilter(PersistenceConstants.PC_MOVIE_SAVE_ERROR);
        if (saveMovieErrorReceiver == null)
            saveMovieErrorReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context localContext, Intent intent) {
                    context.unregisterReceiver(saveMovieErrorReceiver);

                    //Notify the error to Activity
                    context.sendBroadcast(new Intent(BusinessConstants.BC_MOVIE_SAVED_ERROR));
                }
            };
        context.registerReceiver(saveMovieErrorReceiver, saveMovieErrorIntentFilter);

        Movie m = new Movie();

         m.setTitle(title);
        m.setPhotos(photos);
        m.setCategories(categories);
        m.setReleaseDate(releaseDate);
        m.setDescription(description);
        m.setDirector(director);
        m.setWatchList(watchList);
        m.setFavorite(favorite);
        m.setOwnRating(ownRating);
        m.setCoverPhoto(coverPhoto);

        //Make the request
        DatabaseHelper.getInstance().saveMovie(m);

    }

    public void requestUpdateMovie(Long id, String title, Date releaseDate, String description, String director, boolean[] categories, Boolean watchList, Boolean favorite, Float ownRating, Uri coverPhoto, List<Uri> photos) {

           //Register the receivers
           if (updateMovieSuccessIntentFilter == null)
               updateMovieSuccessIntentFilter = new IntentFilter(PersistenceConstants.PC_MOVIES_UPDATED_SUCCESSFULLY);
           if (updateMovieSuccessReceiver == null)
               updateMovieSuccessReceiver = new BroadcastReceiver() {
                   @Override
                   public void onReceive(Context localContext, Intent intent) {
                       context.unregisterReceiver(updateMovieSuccessReceiver);

                       //Notify the success to Activity
                       context.sendBroadcast(new Intent(BusinessConstants.BC_MOVIES_UPDATED_SUCCESSFULLY));
                   }
               };
           context.registerReceiver(updateMovieSuccessReceiver, updateMovieSuccessIntentFilter);

           if (updateMovieErrorIntentFilter == null)
               updateMovieErrorIntentFilter = new IntentFilter(PersistenceConstants.PC_MOVIES_UPDATED_ERROR);
           if (updateMovieErrorReceiver == null)
               updateMovieErrorReceiver = new BroadcastReceiver() {
                   @Override
                   public void onReceive(Context localContext, Intent intent) {
                       context.unregisterReceiver(updateMovieErrorReceiver);

                       //Notify the error to Activity
                       context.sendBroadcast(new Intent(BusinessConstants.BC_MOVIES_UPDATED_ERROR));
                   }
               };
           context.registerReceiver(updateMovieErrorReceiver, updateMovieErrorIntentFilter);

           Movie m = new Movie();

           // NO ID
           if(id <= 0)
                context.sendBroadcast(new Intent(BusinessConstants.BC_MOVIES_NO_ID));
           else
           {
            m.setId(id);
            m.setTitle(title);
            m.setPhotos(photos);
            m.setCategories(categories);
            m.setReleaseDate(releaseDate);
            m.setDescription(description);
            m.setDirector(director);
            m.setWatchList(watchList);
            m.setFavorite(favorite);
            m.setOwnRating(ownRating);
            m.setCoverPhoto(coverPhoto);

            //Make the request
            DatabaseHelper.getInstance().updateMovie(m);
           }

    }


    public void requestDeleteMovie(Long id) {

        if (deleteMovieSuccessIntentFilter == null)
            deleteMovieSuccessIntentFilter = new IntentFilter(PersistenceConstants.PC_MOVIE_DELETED_SUCCESSFULLY);
        if (deleteMovieSuccessReceiver == null)
            deleteMovieSuccessReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context localContext, Intent intent) {
                    context.unregisterReceiver(deleteMovieSuccessReceiver);

                    //Notify the success to Activity
                    context.sendBroadcast(new Intent(BusinessConstants.BC_MOVIES_DELETED_SUCCESSFULLY));
                }
            };
        context.registerReceiver(deleteMovieSuccessReceiver, deleteMovieSuccessIntentFilter);

        if (deleteMovieErrorIntentFilter == null)
            deleteMovieErrorIntentFilter = new IntentFilter(PersistenceConstants.PC_MOVIE_DELETED_ERROR);
        if (deleteMovieErrorReceiver == null)
            deleteMovieErrorReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context localContext, Intent intent) {
                    context.unregisterReceiver(deleteMovieErrorReceiver);

                    //Notify the error to Activity
                    context.sendBroadcast(new Intent(BusinessConstants.BC_MOVIES_DELETED_ERROR));
                }
            };
        context.registerReceiver(deleteMovieErrorReceiver, deleteMovieErrorIntentFilter);

        //Make the request
        DatabaseHelper.getInstance().deleteMovie(id);
    }

    public void searchMovies(String s)
    {
        if (getMoviesFromSearchSuccessIntentFilter == null)
            getMoviesFromSearchSuccessIntentFilter = new IntentFilter(PersistenceConstants.PC_MOVIES_FROM_SEARCH_SUCCESSFULLY);
        if (getMoviesFromSearchSuccessReceiver == null)
            getMoviesFromSearchSuccessReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context localContext, Intent intent) {
                    context.unregisterReceiver(getMoviesFromSearchSuccessReceiver);
                    moviesList = DatabaseHelper.result;
                    // send the intent to notify the success
                    context.sendBroadcast(new Intent(BusinessConstants.BC_MOVIES_FROM_SEARCH_SUCCESSFULLY));
                }
            };
        context.registerReceiver(getMoviesFromSearchSuccessReceiver,getMoviesFromSearchSuccessIntentFilter);

        //Make the request
        DatabaseHelper.getInstance().searchMovies(s);
    }

    public Movie getMovieById(Long movieID)
    {
        if (getMovieByIdSuccessIntentFilter == null)
            getMovieByIdSuccessIntentFilter = new IntentFilter(PersistenceConstants.PC_MOVIE_GETBYID_SUCCESSFULLY);
        if (getMovieByIdSuccessReceiver == null)
            getMovieByIdSuccessReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context localContext, Intent intent) {
                    context.unregisterReceiver(getMovieByIdSuccessReceiver);
                    movie=DatabaseHelper.getInstance().getMovie();
                    //Notify the success to Activity
                    context.sendBroadcast(new Intent(BusinessConstants.BC_MOVIES_GETBYID_SUCCESSFULLY));
                    context.sendBroadcast(new Intent(ViewConstants.VIEW_MOVIE_GETBYID_SUCCESSFULLY));
                }
            };
        context.registerReceiver(getMovieByIdSuccessReceiver, getMovieByIdSuccessIntentFilter);

        if (getMovieByIdErrorIntentFilter == null)
            getMovieByIdErrorIntentFilter = new IntentFilter(PersistenceConstants.PC_MOVIE_GETBYID_ERROR);
        if (getMovieByIdErrorReceiver == null)
            getMovieByIdErrorReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context localContext, Intent intent) {
                    context.unregisterReceiver(getMovieByIdErrorReceiver);

                    //Notify the success to Activity
                    context.sendBroadcast(new Intent(BusinessConstants.BC_MOVIE_GETBYID_ERROR));
                }
            };
        context.registerReceiver(getMovieByIdErrorReceiver, getMovieByIdErrorIntentFilter);


        //Make the request
        DatabaseHelper.getInstance().getMovieById(movieID);

        return null;
        //
    }


    public void requestMovies(ApplicationVariables.RequestMoviesTypes type)
    {
        // register the receivers
        if (receiveFoldersSuccessIntentFilter == null)
            receiveFoldersSuccessIntentFilter = new IntentFilter(PersistenceConstants.PC_FOLDERS_RECEIVED_SUCCESSFULLY);
        if (receiveFoldersSuccessReceiver == null)
            receiveFoldersSuccessReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context localContext, Intent intent) {
                    // unregister the receiver
                    context.unregisterReceiver(receiveFoldersSuccessReceiver);

                    // get the array list
                    moviesList = DatabaseHelper.result;

                    // send the intent to notify the success
                    context.sendBroadcast(new Intent(BusinessConstants.BC_FOLDERS_RECEIVED_SUCCESSFULLY));
                }
            };
        context.registerReceiver(receiveFoldersSuccessReceiver,receiveFoldersSuccessIntentFilter);


        // make the request
        switch (type)
        {
            case ALPHABETICALLY:
                DatabaseHelper.getInstance().getMoviesAlphabetically();
                break;
            case COLLECTIONS:
                DatabaseHelper.getInstance().getMoviesByCollections();
                break;
            case RELEASE_YEAR:
                DatabaseHelper.getInstance().getMoviesByReleaseYear();
                break;
            case GENRES:
                DatabaseHelper.getInstance().getMoviesGenre();
                break;
        }

    }

    public void requestMoviesInsideFolder(ApplicationVariables.RequestMoviesTypes type, String param)
    {
        // register the receivers
        if (receiveMoviesSuccessIntentFilter == null)
            receiveMoviesSuccessIntentFilter = new IntentFilter(PersistenceConstants.PC_MOVIES_RECEIVED_SUCCESSFULLY);
        if (receiveMoviesSuccessReceiver == null)
            receiveMoviesSuccessReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context localContext, Intent intent) {
                    // unregister the receiver
                    context.unregisterReceiver(receiveMoviesSuccessReceiver);

                    // get the array list
                    moviesList = DatabaseHelper.result;

                    // send the intent to notify the success
                    context.sendBroadcast(new Intent(BusinessConstants.BC_MOVIES_RECEIVED_SUCCESSFULLY));
                }
            };
        context.registerReceiver(receiveMoviesSuccessReceiver,receiveMoviesSuccessIntentFilter);


        // make the request
        switch (type)
        {
            case ALPHABETICALLY:
                DatabaseHelper.getInstance().getMoviesForALetter(param);
                break;
            case COLLECTIONS:
                DatabaseHelper.getInstance().getMoviesForACollection(Integer.valueOf(param));
                break;
            case RELEASE_YEAR:
                DatabaseHelper.getInstance().getMoviesForAYear(Integer.valueOf(param));
                break;
            case GENRES:
                DatabaseHelper.getInstance().getMoviesForAGenre(Integer.valueOf(param));
                break;
        }

    }

    public List<CoverFlowElement> getMoviesList()
    {
        return moviesList;
    }

    public Movie getMovie()
    {
            return DatabaseHelper.getInstance().getMovie();
    }

}
